<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料计划编号" prop="sn" label-width="55">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入物料计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['mes:requirement:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['mes:requirement:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:requirement:export']"
        >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="requirementList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="需求单id" align="center" prop="id" />-->
      <el-table-column label="序号" align="center" prop="number" width="90" />
      <el-table-column label="采购状态" align="center" prop="state"width="90" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.requirement_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="物料计划编码" align="center" prop="sn" />
      <el-table-column label="销售订单编号" align="center" prop="orderSn" />
      <el-table-column label="产品编号" align="center" prop="proSn" />
      <el-table-column label="产品名称" align="center" prop="proName" />
      <el-table-column label="计划截止日期" align="center" prop="planEndDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row,scope.$index)"
            v-hasPermi="['mes:requirement:edit']"
          >生成采购订单</el-button>
          <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <el-icon class="el-icon-more">
                  </el-icon>
                  更多
                </span>
            <template #dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-check"
                  >查看详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['mes:requirement:remove']"
                >删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['mes:requirement:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购需求对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="订单编号" prop="orderSn">-->
<!--          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="需求数量" prop="reqNum">-->
<!--          <el-input v-model="form.reqNum" placeholder="请输入需求数量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="采购状态" prop="state">-->
<!--          <el-input v-model="form.state" placeholder="请输入采购状态" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="计划截止日期" prop="planEndDate">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.planEndDate"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择计划截止日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

    <!-- 下达采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item>
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" v-loading="loading" border :data="orderList" :rules="rules">
              <el-table-column label="物料名称" prop="matName" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.matName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="物料编码" prop="matSn" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.matSn}}</span>
                </template>
              </el-table-column>
              <el-table-column label="采购数量" prop="reqNum" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.reqNum}}</span>
                </template>
              </el-table-column>
              <el-table-column label="采购员" prop="userId" align="center">
                <template slot-scope="scope">
                    <el-select v-model="scope.row.userId" placeholder="请选择销售员" style="width: 100%;" >
                      <el-option
                        v-for="item in UserList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId">
                      </el-option>
                    </el-select>
                </template>
              </el-table-column>
              <el-table-column label="供应商" prop="supplierId" align="center" >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.supplierId" placeholder="请选择供应商" style="width: 100%;" >
                    <el-option
                      v-for="item in supplierList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequirement, getRequirement, delRequirement, addRequirement, updateRequirement, getOrder } from "@/api/mes/requirement";
import {listSupplier} from "@/api/mes/supplier";
import {listUser} from "@/api/system/user";
import {addPurchaseOrder} from "@/api/mes/order";
import Vue from "vue";

export default {
  name: "Requirement",
  dicts:["requirement_state"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购需求表格数据
      requirementList: [],
      //采购员信息表数据
      UserList:[],
      //查询供应商信息
      supplierList:[],
      //新增采购订单
      purchaseOrderList:[],
      //生成采购订单列表
      orderList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId:[ { required: true, message: '请选择用户ID', trigger: ['change'] }],
        supplierId:[ { required: true, message: '请选择供应商ID', trigger: ['change'] }],
      }
    };
  },
  created() {
    this.getList();
    this.getCustInfoList()
    this.getUserList()
  },
  methods: {
    /** 查询采购需求列表 */
    getList() {
      this.loading = true;
      listRequirement(this.queryParams).then(response => {
        this.requirementList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.requirementList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    /** 查询供应商列表信息 */
    getCustInfoList() {
      listSupplier(this.queryParams).then(response => {
        this.supplierList = response.rows;
      });
    },
    /** 查询销售员信息列表 */
    getUserList() {
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
        console.log("客户信息列表", this.UserList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materId: null,
        orderSn: null,
        proId: null,
        reqNum: null,
        state: null,
        planEndDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购需求";
    },
    /** 修改按钮操作 */
    handleUpdate(row,index) {
      this.reset();
      const id = row.id || this.ids
      const proId = row.proId
      getRequirement(id).then(response => {
        this.form = response.data;
        this.Index=index,
        this.open = true;
        this.title = "生成采购订单";
      });
      getOrder(proId).then(response => {
        this.orderList=response
        console.log("this.orderList",this.orderList)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.orderList.forEach((item,index)=>{
        Vue.set(this.purchaseOrderList,index,{
          orderId:this.requirementList[this.Index].orderId,
          proId:this.requirementList[this.Index].proId,
          bomId:item.bomId,
          matId:item.matId,
          userId:item.userId,
          supplierId:item.supplierId,
          reqNum:item.reqNum,
        });
      });
      addPurchaseOrder(this.purchaseOrderList).then(response =>{
        this.$modal.msgSuccess("采购订单添加成功");
        this.purchaseOrderList = [];
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购需求编号为"' + ids + '"的数据项？').then(function() {
        return delRequirement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/requirement/export', {
        ...this.queryParams
      }, `requirement_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
